<template>
  <div>
    <el-card class="search-card">
      <BasicTableForm
        ref="formData"
        defaultExpandStatus
        isScalingBtn
        :colNumOfRow="4"
        :formColumns="formItemList"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
      />
    </el-card>
    <el-card class="table-card">
      <skus-table
        :loading="tableInfo.loading"
        showSelectCol
        showActionCol
        :showPagination="isShowPagination"
        :tableHeight="480"
        :actionColWidth="200"
        :defaultMinWidth="100"
        :dataSource="tableInfo.list"
        :columns="tableInfo.columns"
        :pageSizes="pageSizes"
        :pagination="pagination"
        :total="total"
        :selectionChange="handleSelectionChange"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
      >
        <div slot="content_context">
          <BtnRender :render="renderBtnsBar" />
        </div>
      </skus-table>
    </el-card>
    <!-- 添加仓库 -->
    <AddStorehouseDialog
      :visible.sync="dialogVisible.addAtorehouse"
      :uuidList="selectionUuids"
    />
    <!-- 上架提示弹框 -->
    <ActionDialog
      isShowOffRadio
      actionType="1"
      dialogTitle="上架提示"
      :visible.sync="dialogVisible.batchUp"
      :okLoading="btnLoading.batchUp"
      :handleSubmit="batchUpTemporaryProjectGoods"
    />
    <!-- 停用提示弹框 -->
    <DisuseDialog
      :visible.sync="dialogVisible.batchOff"
      :okLoading="btnLoading.batchOff"
      :handleSubmit="batchOffTemporaryProjectGoods"
    />
    <!-- 修改预计下架日期弹框 -->
    <ActionDialog
      isShowOffRadio
      actionType="2"
      dialogTitle="修改预计下架日期"
      :visible.sync="dialogVisible.changeOffTime"
      :okLoading="btnLoading.changeOffTime"
      :handleSubmit="batchUpdateOffDate"
    />
    <!-- 修改日志弹框 -->
    <ChangeLogDialog
      :skuNo="viewChangeLog.skuNo"
      :visible.sync="dialogVisible.viewChangeLog"
    />
    <!-- 高级关联 -->
    <SeniorLinkedDialog
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="getTableDataBySenior"
    />
  </div>
</template>
<script>
import BasicTableForm from '@/components/BasicForm';
import RemoteSelect from '@/pages/commodity/components/RemoteSelect';
import SkusTable from '@/components/skusTable';
import AddStorehouseDialog from '../components/AddStorehouseDialog';
import ActionDialog from '../components/ActionDialog';
import DisuseDialog from '../components/DisuseDialog';
import ChangeLogDialog from '../components/ChangeLogDialog';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import BtnRender from '@/components/JSXRender/BtnRender';
import { getBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import { FORM_ITEM_LIST, TABLE_COLUMNS } from './constants';
import { PRODUCT_TYPES_ENUMS } from '@/constants/commodity';
import { handleOpenNewPage, setAuthBtnId, createExcelByExport } from '@/utils/bizUtils';
import { getSearchParamBySearchType } from '@/utils/getUtils';
import skusPage from '@/mixins/commodity/skusPage';
import {
  exportSkuListService,
  queryDetailBySourcingNoService,
  batchPutOnShelvesService,
  batchPullOnShelvesService,
  batchUpdateOffTimeService,
  queryChangeLogBySkuNoService,
  queryEditPermissionService,
  getSeniorLinkedCollectListService,
} from '@/api/commodity/temporaryPurchasingGoods/temporaryPurchaseGoods';

export default {
  mixins: [ skusPage ],
  components: {
    BasicTableForm,
    SkusTable,
    BtnRender,
    RemoteSelect,
    AddStorehouseDialog,
    ActionDialog,
    DisuseDialog,
    ChangeLogDialog,
    SeniorLinkedDialog,
  },
  data () {
    return {
      formData: {
        recordNo: '', // 单据号
        categoryUuid: '', // 四级类名称
        skuNo: '', // SKU编码
        brandName: '', // 品牌
        productName: '', // 商品名称
        createOper: '', // 创建人
        operDeptUuid: '', // 创建人部门
        createOpeTime: '', // 创建时间
        expectOffTime: '', // 预计下架时间
        upState: '1', // 上下架状态
        imageStatus: '', // 图文完善状态
        createOpeTimeStart: '',
        createOpeTimeEnd: '',
        expectOffTimeStart: '',
        expectOffTimeEnd: ''
      },
      formItemList: FORM_ITEM_LIST,
      tableInfo: {
        list: [],
        selection: [],
        columns: TABLE_COLUMNS,
        loading: false
      },
      pageSizes: [10, 100, 1000],
      dialogVisible: {
        batchUp: false,
        batchOff: false,
        changeOffTime: false,
        viewChangeLog: false,
        addAtorehouse: false
      },
      btnLoading: {
        batchUp: false,
        batchOff: false,
        changeOffTime: false,
        export: false,
      },
      showList: {
        loading: false,
        columns: [],
        list: []
      },
      viewChangeLog: {
        skuNo: ''
      },
      isShowPagination: true, // 是否展示分页，默认展示
      seniorLinked: {
        visible: false,
        columns: [{ label: 'SKU编码', prop: 'skuNo', type: 'textarea' }],
        dataSource: [{ skuNo: '' }]
      }
    };
  },
  created () {
    this.getTableData();
  },
  computed: {
    isToBatchUp () {
      const isEmptyTable = this.tableInfo.list.length === 0;
      if (isEmptyTable) return this.formData.upState === '2';
      const isShowUpSku = this.tableInfo.list[0].upState === '2';
      return isShowUpSku; // 当前展示上架时，展示下架按钮，反之展示上架按钮
    },
    hasNoSelection () {
      return this.tableInfo.selection.length === 0;
    },
    selectionUuids () {
      return this.tableInfo.selection.map(item => item.uuid);
    }
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const batchUpBtn = { label: '批量上架', method: this.handleBatchUp };
      const batchDownBtn = { label: '批量下架', method: this.handleBatchDown, loading: this.btnLoading.batchOff };
      const batchChangeTimeBtn = { label: '修改下架日期', method: this.handleEditDownDate };
      const btnsBar = [
        { label: '高级关联', method: this.handleSeniorLinked, disabled: false },
        { label: '导出', method: this.handleExportTemplate, disabled: false, loading: this.btnLoading.export },
        { label: '批量新增', method: this.handleBatchAdd, disabled: false },
        { label: '批量编辑', method: this.handleBatchEdit },
        this.isToBatchUp ? batchUpBtn : batchDownBtn,
        !this.isToBatchUp && batchChangeTimeBtn,
        { label: '添加库房', method: this.handleAddStoreroom }
      ];
      // 按钮通用属性填充
      const finalBars = btnsBar.filter(item => item).map(item => ({
        ...item,
        type: 'primary',
        size: 'mini',
        disabled: item.disabled ?? this.hasNoSelection,
        hasAuth: item.hasAuth ?? true
      }));
      return getBtnsBar(h, finalBars, this.showBtn, 'start');
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const actionList = [
        { label: '图文查看', method: this.handleViewImageText },
        { label: '图文编辑', method: this.handleEditImageText, hasAuth: true },
        { label: '修改日志', method: this.handleEditLog },
      ]
      return getTableAction({ h, row, actionList, showBtn: this.showBtn })
    },
    // 勾选需要处理的库存
    handleSelectionChange (rows) {
      this.tableInfo.selection = rows;
    },
    // 获取查询入参
    getSearchParams () {
      const [createOpeTimeStart = '', createOpeTimeEnd = ''] = this.formData.createOpeTime ?? [];
      const [expectOffTimeStart = '', expectOffTimeEnd = ''] = this.formData.expectOffTime ?? [];
      const timeArr = [
        {name: 'createOpeTimeStart', value: createOpeTimeStart},
        {name: 'createOpeTimeStart_q', value: 'EQ'},
        {name: 'createOpeTimeEnd', value: createOpeTimeEnd},
        {name: 'createOpeTimeEnd_q', value: 'EQ'},
        {name: 'expectOffTimeStart', value: expectOffTimeStart},
        {name: 'expectOffTimeStart_q', value: 'EQ'},
        {name: 'expectOffTimeEnd', value: expectOffTimeEnd},
        {name: 'expectOffTimeEnd_q', value: 'EQ'},
      ]
      return timeArr;
    },
    // 获取表格数据
    async getTableData () {
      const formData = _.omit({
        ...this.formData,
      }, ['createOpeTime', 'expectOffTime']);
      let data = {
        searchParam: JSON.stringify(getSearchParamBySearchType(FORM_ITEM_LIST, formData).concat(this.getSearchParams())),
        ...this.paginationParams
      };
      setAuthBtnId();
      const res = await queryDetailBySourcingNoService(
        data,
        state => { this.tableInfo.loading = state }
      );
      if (res?.retData) {
        this.tableInfo.list = res.retData.results;
        this.total = res.retData.totalNum;
      }
    },
    // 添加库房
    handleAddStoreroom () {
      const callbackFn = () => { this.dialogVisible.addAtorehouse = true }
      this.queryEditPermission('添加库房', callbackFn)
    },
    // 图文查看
    handleViewImageText (row) {
      this.skipToImagePage(row, 'view');
    },
    // 图文编辑
    handleEditImageText (row) {
      this.tableInfo.selection.push(row)
      const callbackFn = () => { this.skipToImagePage(row, 'edit') }
      this.queryEditPermission('批量编辑', callbackFn)
    },
    // 修改日志
    handleEditLog (row) {
      this.dialogVisible.viewChangeLog = true;
      this.viewChangeLog.skuNo = row.skuNo;
    },
    // 批量新增
    handleBatchAdd () {
      this.$router.push({
        name: 'temporaryAddCode',
        query: { type: 1 }
      });
    },
    // 批量编辑
    handleBatchEdit () {
      const callbackFn = () => {
        // 判断是否存在草稿状态单据
        if (this.tableInfo.selection.some(item => item.productAddState == 1)) {
          const recordNoList = [...new Set(this.tableInfo.selection.map(item => item.recordNo))]
          const sourceType = this.tableInfo.selection[0].source
          if (recordNoList.length !== 1 ) {
            this.$message.warning('存在草稿状态单据，勾选项单据号必须一致')
          } else {
            this.$router.push({ name: 'temporaryAddCode', query: { type: 4, sourceType }, params: { uuids: this.selectionUuids } })
          }
        } else {
          this.$router.push({ name: 'temporaryGoodsEdit', params: { uuids: this.selectionUuids } })
        }
      }
      this.queryEditPermission('批量编辑', callbackFn)
    },
    // 批量上架
    handleBatchUp () {
      const callbackFn = () => { this.dialogVisible.batchUp = true }
      this.queryEditPermission('批量编辑', callbackFn)
    },
    // 批量下架
    handleBatchDown () {
      const callbackFn = () => {
        this.dialogVisible.batchOff = true
      }
      this.queryEditPermission('批量编辑', callbackFn)
    },
    // 修改下架日期
    handleEditDownDate () {
      const callbackFn = () => { this.dialogVisible.changeOffTime = true }
      this.queryEditPermission('批量编辑', callbackFn)
    },
    // 跳转图文页面
    skipToImagePage (row, type) {
      handleOpenNewPage(this, {
        name: 'imageTextManage',
        query: {
          skuId: row.uuid,
          skuNo: row.skuNo,
          type,
          productType: PRODUCT_TYPES_ENUMS.TEMP
        }
      })
    },
    // 批量上架临时项目商品
    async batchUpTemporaryProjectGoods (result) {
      const { expectOffTime } = result;
      // operType	操作类型 1-立即上架，2-手动上架 expectOffTime	下架时间
      this.batchAction('batchUp', { operType: 2, expectOffTime, offTimeType: expectOffTime ? 1 : 2 });
    },
    // 批量下架临时项目商品
    async batchOffTemporaryProjectGoods (param) {
      this.batchAction('batchOff', param);
    },
    // 批量修改下架日期
    async batchUpdateOffDate (result) {
      const { expectOffTime } = result;
      // expectOffTime - 预计下架日期 下架类型 1-到期下架，2-永不下架，3-售完下架
      this.batchAction('changeOffTime', { expectOffTime, offTimeType: expectOffTime ? 1 : 2 });
    },
    // 获取批量操作的实例对象
    getBatchActionInstance (type) {
      const batchUp = {
        msg: '上架成功',
        authName: '批量上架',
        request: batchPutOnShelvesService,
      }
      const batchOff = {
        msg: '下架成功',
        authName: '批量下架',
        request: batchPullOnShelvesService,
      }
      const changeOffTime = {
        msg: '下架日期修改成功',
        authName: '修改下架日期',
        request: batchUpdateOffTimeService
      }
      const actionMaps = { batchUp, batchOff, changeOffTime };
      return actionMaps[type] ?? {};
    },
    // 批量操作请求
    async batchAction (type, params) {
      const { msg, request, authName } = this.getBatchActionInstance(type);
      if (authName) setAuthBtnId(authName);
      const loadingFn = state => { this.btnLoading[type] = state };
      const data = {
        ...params,
        uuids: this.selectionUuids
      }
      const res = await request(data, loadingFn);
      if (res) {
        this.$message.success(msg);
        if (this.dialogVisible[type]) {
          this.dialogVisible[type] = false;
        }
        this.getTableData();
      }
    },
    // 获取修改日志列表
    async getEditLogsList (skuNo) {
      const loadingFn = state => { this.showList.loading = state };
      const data = { skuNo };
      const res = await queryChangeLogBySkuNoService(data, loadingFn);
      if (res) {
        this.showList.list = res.retData;
      }
    },
    // 导出模板
    async handleExportTemplate () {
      const [createOpeTimeStart = '', createOpeTimeEnd = ''] = this.formData.createOpeTime;
      const [expectOffTimeStart = '', expectOffTimeEnd = ''] = this.formData.expectOffTime;
      const data = {
        ...this.formData,
        createOpeTimeStart,
        createOpeTimeEnd,
        expectOffTimeStart,
        expectOffTimeEnd
      }
      const res = await exportSkuListService(data, state => { this.btnLoading.export = state });
      createExcelByExport({ res, excelTitle: '线索商品' });
    },
    // 高级关联
    handleSeniorLinked () {
      this.seniorLinked.visible = true;
    },
    // 高级关联
    async getTableDataBySenior (skuNos) {
      this.isShowPagination = false;
      setAuthBtnId('高级关联');
      const data = { skuNos };
      const loadingFn = state => { this.tableInfo.loading = state };
      const retData = await getSeniorLinkedCollectListService(data, loadingFn);
      console.log(retData)
      if (retData) {
        this.tableInfo.list = retData;
      }
    },
    // 获取修改权限
    async queryEditPermission (btnName, callback) {
      setAuthBtnId(btnName);
      const loadingFn = state => { this.showList.loading = state };
      const res = await queryEditPermissionService(this.selectionUuids, loadingFn);
      if (res && res.retData) {
        const { retData } = res;
        if (retData.length == 0) {
          callback()
        } else {
          this.$message(`商品${retData}不是您部门发起，您无权操作`)
        }
      }
    },
  }
};
</script>
